<html>
    <head>
        <style type="text/css">
            body {margin:0;padding:0;font-family: arial; font-size:11pt; color:white; background:#4b4b4b; background-image:url(/images/installtoplogo/back.gif); background-position:top; background-repeat:repeat-x}
            div.oknotice,span.ok { color:#bfb }
            div.failednotice,span.failed { color:#f88;font-weight:bold}
            div.oknotice { text-align:center}
            div.failednotice {text-align:center}
        </style>
        <script type="text/javascript">

            function randomString() {
                var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
                var string_length = Math.random() * 10 + 10;
                var result = '';
                for (var i=0; i<string_length; i++) {
                        var rnum = Math.floor(Math.random() * chars.length);
                        result += chars.substring(rnum,rnum+1);
                }
                return result;
            }


            function generateSalt() {
                document.getElementById('sha1_salt').setAttribute('value',randomString());
            }
            </script>
    </head>
<body>
    <div style="text-align:center"><img src='/images/installtoplogo/title.jpg' style="padding-right:150px"/></div>
    <div style="position:absolute;top:150px;padding-left:30px;width:90%;overflow:hidden;z-index:200">
        <div style="text-decoration:underline;font-size:18pt;">Installation</div>
<?php

if (isset($_GET['install']) && $_GET['install'] == 'now'):
        define('APPLICATION_PATH', realpath(__DIR__ . DIRECTORY_SEPARATOR.'..').DIRECTORY_SEPARATOR.'application');
        define('DOCUMENT_ROOT', realpath(__DIR__));

        set_include_path(get_include_path().PATH_SEPARATOR.realpath(__DIR__.DIRECTORY_SEPARATOR.'..').DIRECTORY_SEPARATOR.'library');
        $filesSaveIniFile=realpath(__DIR__.DIRECTORY_SEPARATOR.'..').DIRECTORY_SEPARATOR.'application'.DIRECTORY_SEPARATOR.'configs'.DIRECTORY_SEPARATOR.'files.ini';
        $filesIniFile=realpath(__DIR__.DIRECTORY_SEPARATOR.'..').DIRECTORY_SEPARATOR.'application'.DIRECTORY_SEPARATOR.'configs'.DIRECTORY_SEPARATOR.'files.ini.default';
        $iniFile=realpath(__DIR__.DIRECTORY_SEPARATOR.'..').DIRECTORY_SEPARATOR.'application'.DIRECTORY_SEPARATOR.'configs'.DIRECTORY_SEPARATOR.'application.ini.default';
        $saveIniFile=realpath(__DIR__.DIRECTORY_SEPARATOR.'..').DIRECTORY_SEPARATOR.'application'.DIRECTORY_SEPARATOR.'configs'.DIRECTORY_SEPARATOR.'application.ini';
        $xmlFile=realpath(__DIR__.DIRECTORY_SEPARATOR.'..').DIRECTORY_SEPARATOR.'application'.DIRECTORY_SEPARATOR.'xml'.DIRECTORY_SEPARATOR.'navigation.xml.default';
        $xmlSaveFile=realpath(__DIR__.DIRECTORY_SEPARATOR.'..').DIRECTORY_SEPARATOR.'application'.DIRECTORY_SEPARATOR.'xml'.DIRECTORY_SEPARATOR.'navigation.xml';
        $schemaSql=realpath(__DIR__.DIRECTORY_SEPARATOR.'..').DIRECTORY_SEPARATOR.'scripts'.DIRECTORY_SEPARATOR.'schema.mysql.sql';
        $dataSql=realpath(__DIR__.DIRECTORY_SEPARATOR.'..').DIRECTORY_SEPARATOR.'scripts'.DIRECTORY_SEPARATOR.'data.mysql.sql';

        require_once('Zend/Config/Ini.php');
        require_once('Zend/Config/Writer/Ini.php');
        require_once('Zend/Db.php');
        require_once('Zend/Db/Table/Abstract.php');

        $sha1Salt=$_POST['sha1_salt'];
        $adminPassword=$_POST['admin_password'];
        $dbAdapter=$_POST['db_adapter'];
        $dbHost=$_POST['db_host'];
        $database=$_POST['database'];
        $dbuser=$_POST['db_username'];
        $dbpassword=$_POST['db_password'];

$params = array(
        'host'           => $dbHost,
        'username'       => $dbuser,
        'password'       => $dbpassword,
        'dbname'         => $database,
    );

        $db = Zend_Db::factory($dbAdapter, $params);
    //Zend_Db_Table_Abstract::setDefaultAdapter($db);

        if (!is_file($iniFile)) {
            die("could not find application.ini.defaults in application/configs directory.");
        }
        if (!is_file($schemaSql)) {
            die("could not find schema.mysql.sql in scripts directory.");
        }
        if (!is_file($dataSql)) {
            die("could not find data.mysql.sql in scripts directory.");
        }

        if (!is_file($filesIniFile)) {
            die("could not find files.ini.default in application/configs directory.");
        }
        echo "found all relevant files</br>";
        $config = new Zend_Config_Ini($iniFile,null,array('skipExtends'        => true,
                                                          'allowModifications' => true));
        $config->production->security->sha1->salt=$sha1Salt;
        $config->production->resources->db->adapter=$dbAdapter;
        $config->production->resources->db->params->host=$dbHost;
        $config->production->resources->db->params->username=$dbuser;
        $config->production->resources->db->params->password=$dbpassword;
        $config->production->resources->db->params->dbname=$database;

        $writer = new Zend_Config_Writer_Ini(array('config'=>$config,'filename'=>$saveIniFile));
        $writer->write();
        echo 'saved new application.ini<br/>';
        $schema=explode(';',file_get_contents($schemaSql));
        foreach ($schema as $sql) {
            if (trim($sql) == '')
                   continue;
            try {
                $db->query($sql);
            } catch (Exception $e) {
                die('Error Installing DB: '.$e->getMessage()." for query: '$sql'");
            }
        }
        echo 'installed schema into db<br/>';
        $data = explode(';',file_get_contents($dataSql));

        foreach ($data as $sql) {
            if (trim($sql) == '')
                   continue;
            try {
                $db->query($sql);
            } catch (Exception $e) {
                die('Error Installing DB: '.$e->getMessage()." for query: '$sql'");
            }
        }

        $db->update('users', array('password'=>sha1($sha1Salt.$adminPassword)),'username = \'admin\'');
        echo 'updated new admin password<br/>';

        echo 'installed data into db<br/>';
        if (!copy($xmlFile,$xmlSaveFile)) {
            die("Error: Could not copy navigation.xml.default to navigation.xml");
        }
        echo 'created navigation.xml<br/>';
        if (!copy($filesIniFile,$filesSaveIniFile)) {
            die("Error: could not copy files.ini.default to files.ini!");
        }
        echo 'created files.ini<br/>';
        echo '<h2>done. please login as admin user to finish installation!</h2>';


else:



$failures = 0;
$zfok=true;
$zfmessage='';
$zfversion=0;

function checkZF() {
    global $zfok;
    global $zfmessage;
    global $zfversion;
    global $failures;
    $versionFile=realpath(__DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'library'.DIRECTORY_SEPARATOR.'Zend').DIRECTORY_SEPARATOR.'Version.php';
    if (!is_file($versionFile)) {
        $zfok=false;
        $zfmessage= 'Zend Framework not found in library directory (missing library/Zend/Version.php file)';
        $failures++;
    } else {
        try {
            require($versionFile);
        } catch (Exception $e) {
            $zfok=false;
            $zfmessage='Could not load Version file from Zend Framework.';
            $failures++;
            return;
        }
        $zfversion=Zend_Version::VERSION;
    }
        
}

function checkSystem($function,$okMessage,$failedMessage) {
    global $failures;
    if ($function()) {
        return '<span class="ok">'.$okMessage.'</span>';
    } else {
        $failures++;
        return '<span class="failed">'.$failedMessage.'</span>';
    }
}

checkZF();
?>

    <h3>Checking System:</h3>
<ul>
    <li>PHP Version: <?=checkSystem(function() {return (substr(phpversion(),0,3) == '5.3');}, phpversion().' - Ok','Please upgrade to version 5.3')?></li>
    <li>PHP Json Version: <?=checkSystem(function(){ return (phpversion('json') != false); }, phpversion('json').' - Ok' ,'Not Found!')?></li>
    <li>PHP Iconv - <?=checkSystem(function(){ return function_exists('iconv_strlen'); }, 'Ok' ,'Not Found!')?><li/>
    <li>PHP SimpleXML - <?=checkSystem(function(){ return function_exists('s implexml_load_file'); },phpversion('simplexml').' - Ok','Not Found!')?></li>
    <li>Zend Framework Library - <span <?if ($zfok):?>class="ok"><?=$zfversion?><?else:?>class="failed"><?=$zfmessage?><?endif?></span></li>
</ul>
<h3>PHP configuration requirements (php.ini)</h3>
<ul>
    <li>short open tag support (short_open_tag should be on) - <?=checkSystem(function(){return (ini_get('short_open_tag'));},'On','Off')?></li>
    <li>Safe mode (safe_mode should be off) - <?=checkSystem(function(){return (!ini_get('safe_mode'));},'Off','On')?></li>
    <li>Memory Limit (memory_limit should be at least 128M) - <?=checkSystem(function(){ return (rtrim(ini_get('memory_limit'),'M') >=128);},ini_get('memory_limit'),ini_get('memory_limit'));?>

</ul>

<h3>Directories Permissions</h3>
<ul>
    <li>[doc_root]/public/components should be writeable: <?=checkSystem(function(){return is_writable(__DIR__.DIRECTORY_SEPARATOR.'components');},'Ok','Not writeable')?></li>
    <li>[doc_root]/public/images/groups should be writeable: <?=checkSystem(function(){return is_writable(__DIR__.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'groups');},'Ok','Not writeable')?></li>
    <li>[doc_root]/application/configs should be writeable: <?=checkSystem(function(){return is_writable(__DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'application'.DIRECTORY_SEPARATOR.'configs');},'Ok','Not writeable')?></li>
    <li>[doc_root]/application/xml should be writeable: <?=checkSystem(function(){return is_writable(__DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'application'.DIRECTORY_SEPARATOR.'xml');},'Ok','Not writeable')?></li>
    <li>[doc_root]/application/themes should be writeable: <?=checkSystem(function(){return is_writable(__DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'application'.DIRECTORY_SEPARATOR.'themes');},'Ok','Not writeable')?></li>
</ul>
<br/>
<hr/>
<? if ($failures == 0):?>
<div class="oknotice">Your system is configured properly for installation.<br/>
</div>
<br/>
<form method="post" action="?install=now" name="install_form">
<table>
    <tr><td>SHA1 Salt:</td><td><input type="text" size="20" name="sha1_salt" id="sha1_salt"/>&nbsp;<input type="button" value="generate" onclick="generateSalt()" onclick/></td></tr>
    <tr><td>Admin Password:</td><td><input type="password" name="admin_password"/></td></tr>
    <tr><td>Admin Password (again):</td><td><input type="password" name="admin_password2"/></td></tr>
    <tr><td>DB Adapter:</td><td><input type="text" name="db_adapter" value="PDO_Mysql"/></td></tr>
    <tr><td>DB Host:</td><td><input type="text" name="db_host" value="127.0.0.1"/></td></tr>
    <tr><td>Database:</td><td><input type="text" name="database" value="genesis" /></td></tr>
    <tr><td>DB Username:</td><td><input type="text" name="db_username" value="root"/></td></tr>
    <tr><td>DB Password:</td><td><input type="password" name="db_password" /></td></tr>
    <tr><td></td><td><input type="submit" /></td></tr>
</table>
</form>
<?else:?>
<div class="failednotice">Please fix the problems and try again.<br/>
<input type="button" value="refresh" onclick="location.reload('true')" />
</div>
<?endif;?>
<?endif;?>
    </div>
</body>
</html>
